from operations.exam_operation import ExamOper
import string
from selenium.webdriver.common.by import By
from time import sleep
import re
from logger import logger


class ExamScenarios:
    def __init__(self, driver):
        self.oper = ExamOper(driver)
        self.QA = list()
        self.QO = list()

    def submit(self):
        self.oper.click_submit()
        self.oper.click_confirm()

    def exam_again(self):
        self.oper.click_exam_again()

    def collect_QA_on_paper(self):
        self.submit()
        question_elems = self.oper.get_questions()
        for elem in question_elems:
            title = self.oper.get_title(elem)
            options = self.oper.get_options(elem)
            answer = self.oper.get_answer(elem)
            self.QA.append({
                "title": title.text,
                "options": [option.text for option in options],
                "answer": answer.text
            })
        self.exam_again()
        return self.QA

    def repeat_collect_QA(self, count=15):
        for i in range(count):
            self.QA = self.collect_QA_on_paper()
        return self.QA

    def collect_QO_on_paper(self):
        question_elems = self.oper.get_questions()
        for elem in question_elems:
            title = self.oper.get_title(elem)
            options = self.oper.get_options(elem)
            # answer = self.oper.get_answer(elem)
            self.QO.append({
                "title": title.text,
                "options": [option for option in options],
                # "answer": answer.text
            })
        return self.QO

    def select_option(self, answer, options):
        if answer.isascii():  # choice questions
            answer_set = set(answer)
            for ans in answer_set:
                for option in options:
                    if option.text.startswith(ans):
                        option.click()
                        break
        else:
            for option in options:
                if option.text.startswith(answer):
                    option.click()
                    break

    def find_answer(self):
        for qo in self.QO:
            for index, qa in enumerate(self.QA):
                qa_title = re.split(' ', qa.get('title'), maxsplit=1)[-1]
                qo_title = re.split(' ', qo.get('title'), maxsplit=1)[-1]
                if qa_title == qo_title:
                    answer = qa.get("answer")
                    number = re.search(r"^\d+", qo.get('title')[0:2])
                    self.select_option(answer, qo.get("options"))
                    break
            else:
                answer = ''
                logger.info(f"未作答：{qo.get('title')}")
        # donot_eixt = input("Exit this test?")
        self.submit()
